﻿using System;
using System.Linq;
using System.Web.UI.WebControls;
using Dimebrain.TweetSharp.Model.Twitter;
using NHibernate.Criterion;
using Twipler.App;
using Twipler.App.DataDoc;
using Twipler.App.Entity;
using Twipler.Data.Access;
using Twipler.Data.Cache;
using Twipler.WebApp;
using Dimebrain.TweetSharp.Fluent;
using Page=System.Web.UI.Page;
using Twipler.Data.Entity.Twipler;
using System.Collections.Generic;

namespace TwiplerWeb.Settings.User
{
	[RequireUser()]
	public partial class AccountAlias : Page
	{
        protected void Page_Load(object sender, EventArgs e)
        {
        	if (IsPostBack) 
				return;

            UpdateDisplay();
        }

        private void UpdateDisplay()
        {
            litScreenName.Text = Current.Visitor.ScreenName;
            litToken.Text = Current.SessionTrack.OAuthToken.Token;
            litSecret.Text = Current.SessionTrack.OAuthToken.TokenSecret;

            grdAccounts.DataSource = Current.Visitor.Alias;
            grdAccounts.DataBind();
        }
        
		protected void btnAddAccount_Click(object sender, EventArgs e)
		{
			if ((txtToken.Text.Trim().Length == 0) || (txtSecret.Text.Trim().Length == 0))
			{
				litError.Text = "<div class=errormessage>Please supply the Token and Secret from the account you wish to link.</div>";
				return;
			}

			try
			{
				// Link to myself
				Factory.Alias.SaveOrUpdate( new Twipler.Data.Entity.Twipler.Alias()
				                            	{
				                            		Id = Current.Visitor.Id,
				                            		OtherTwitterId = Current.Visitor.Id,
				                            		OAuthEnc =
				                            			Current.SessionTrack.OAuthToken.Token + " " +
														Current.SessionTrack.OAuthToken.TokenSecret
												});
				
				// Verify other users Token/Secret
				IFluentTwitter caller = FluentTwitter.CreateRequest().AuthenticateWith(Config.ConsumerKey, Config.ConsumerSecret, txtToken.Text.Trim(), txtSecret.Text.Trim());

				TwitterResult result = caller.Account().VerifyCredentials().AsJson().Request();
				DataDocJson doc = new DataDocJson(() => result.Response);

                if (doc.Status == DataDocStatus.Ok)
                {
                    int twitterId = Convert.ToInt32( doc.Find( "/id" ).Value );
                    
                    Factory.Alias.SaveOrUpdate( new Twipler.Data.Entity.Twipler.Alias()
            		                            	{
            		                            		Id = Current.Visitor.Id,
            		                            		OtherTwitterId = (int) twitterId,
            		                            		OAuthEnc = txtToken.Text.Trim() + " " + txtSecret.Text.Trim()
            		                            	} );
					
					using (TableStore<TwitterUserDetails> storeDetails = TableStore<TwitterUserDetails>.Open())
						storeDetails.Add( twitterId, doc.Find("/screen_name").Value as string, doc.Find("/profile_image_url").Value as string );
					
                    

                    litError.Text = "<div class=successmessage>Successfully added account.</div>";

                    UpdateDisplay();

                }
                else
                {
                    litError.Text = "<div class=errormessage>Unable to authenticate the account. Please check the Token and Secret and try again.</div>";
                }
			}
			catch
			{
				litError.Text = "<div class=errormessage>Something exploded. But I think everything is ok.</div>";
			}
		}

		protected void grdAccounts_ItemCommand(object source, DataGridCommandEventArgs e)
		{
			if (e.CommandName == "SwitchTo")
			{
				Me.SwitchTo( int.Parse( e.Item.Cells[ 0 ].Text ) );
                UpdateDisplay();
			}

            if (e.CommandName == "Delete")
            {
                Visitor primaryAccount = Current.Visitor.Alias.FirstOrDefault(t => t.IsPrimaryIdentity);
                if (primaryAccount == null)
                    return;

                List<Alias> candidate = Factory.Alias.GetByCriteria(
                    Restrictions.Eq("Id", primaryAccount.Id),
                    Restrictions.Eq("OtherTwitterId", int.Parse(e.Item.Cells[0].Text)));

                if ((candidate == null) || (candidate.Count() != 1))
                    return;

                Factory.Alias.Delete(candidate[0]);
                UpdateDisplay();
            }
		}

	}
}
